#!/bin/bash

source ${tools_dir}/vm_config.sh

function exit_if_fail() {
    rlt_code=$1
    fail_msg=$2
    if [ $rlt_code -ne 0 ]; then
      echo -e "错误码: ${rlt_code}\n${fail_msg}"
	  whoami
	  exec /bin/bash
      exit $rlt_code
    fi
}

function vm_add_user_droidvm() {
	echo '===================================='
	echo2apk '正在删除rootfs内建的系统登录账户 ...'
	echo '===================================='
	deluser ubuntu
	rm -rf /home/ubuntu

	# 修改 root 用户的密码
	echo 'root:droidvm'    | chpasswd

	# 添加 droidvm 用户，并修改密码
	useradd -m -r -s /bin/bash droidvm
	echo 'droidvm:droidvm' | chpasswd
	mkdir -p /home/droidvm/Desktop/
	mkdir -p /home/droidvm/.droidvm/

	chgrp -R root                /home/droidvm
	chown -R droidvm             /home/droidvm
	chmod -R 0750                /home/droidvm

	echo '===================================='
	echo  '正在给droidvm用户组授以sudo的权限'
	echo '===================================='

	# 修复部分rootfs中droidvm用户不能运行sudo su的问题
	chown root:root /usr/bin/sudo
	chmod 4755 /usr/bin/sudo
	chown root:root /etc/sudo.conf
	chown root:root /etc/sudoers.d
	chmod 4755 /etc/sudoers.d
	chown root:root /run/sudo/ts
	chmod 4755 /run/sudo/ts

	# 2024.10.13 处理 sudo -D 选项无权限使用的问题
	: ' sudoers 文件格式说明
		A       B     = {C}                        {D}                  E
		username  hosts  = target_username/groupt     pwd_required         enabled_commands
		第一部分A代表授权使用sudo的用户或者组
		第二部分B代表允许授权用户在哪些主机上使用这些权利
		第三部分C代表允许被授权用户提权到什么用户什么组级别的权限，如果省略就代表允许提权到任意用户级别。
		第四部分D代表当被授权用户是否需要输入自身密码来使用特权，若省略这代表需要输入密码
		第五部分E代表允许执行的命令，如果是all就代表允许执行所有命令
	'
	chmod 4660											  /etc/sudoers.d/droidvm
	echo 'Defaults:USERLIST   runcwd=*'					> /etc/sudoers.d/droidvm
	echo 'User_Alias  USERLIST = droidvm,ubuntu'		>>/etc/sudoers.d/droidvm
	echo '%droidvm   ALL=(ALL:ALL)           ALL'		>>/etc/sudoers.d/droidvm
	# echo '%droidvm   ALL=(ALL:ALL) NOPASSWD: ALL'		>>/etc/sudoers.d/droidvm
	chmod 4440											  /etc/sudoers.d/droidvm

	echo '===================================='
	echo '正在生成droidvm用户的桌面文件 ...'
	echo '===================================='
	${tools_dir}/vm_builddesktop.sh
}

function vm_copy_autoruns_scripts() {
	echo '===================================='
	echo2apk '正在复制自动运行的脚本 ...'
	echo '===================================='
	cp -Rf /exbin/autoruns /etc/
	mkdir -p /etc/autoruns/autoruns_before_gui 2>/dev/null
	mkdir -p /etc/autoruns/autoruns_after_gui 2>/dev/null
	mkdir -p /etc/autoruns/services_before_gui 2>/dev/null
	mkdir -p /etc/autoruns/services_after_gui 2>/dev/null
	chmod -R 755 /exbin/autoruns
}

function dist_repo_set_ipv4_default() {
	# 优先使用 IPv4 连接 2025.03.16
	mkdir -p /etc/apt/apt.conf.d/ 2>/dev/null
	cat <<- EOF >> /etc/apt/apt.conf.d/1000-force-ipv4-transport
		Acquire::ForceIPv4 "true";
		Acquire::http::Timeout "10";
		Acquire::ftp::Timeout "10";
		Acquire::https::Timeout "10";
		Acquire::Retries "3";
	EOF
}

function dist_repo_setup_sudo() {
	echo2apk '正在获取软件仓库中的软件列表 ...'
	apt update -y

	which sudo >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		apt-get install sudo -y
	fi
}

function dist_repo_setup_ca() {
	# 必须先装 ca-certificates, 否则会报错说第三方仓库不可信
	apt-get install -y ca-certificates
}

function vm_add_bakup_repo_amd64() {
	# 清华源 http://mirrors.tuna.tsinghua.edu.cn/help/debian/
	cat <<- EOF > /etc/apt/sources.list.bak.tsinghua
		# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
	EOF
	REPO_LIST="tsinghua"
}

function vm_add_bakup_repo_arm64() {
	# 清华大学开源软件镜像站 http://mirrors.tuna.tsinghua.edu.cn/help/debian/
	cat <<- EOF > /etc/apt/sources.list.bak.tsinghua
		# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware

		deb http://mirrors.tuna.tsinghua.edu.cn/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
		# deb-src http://mirrors.tuna.tsinghua.edu.cn/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
	EOF

	# 北京外国语大学开源软件镜像站 http://mirrors.bfsu.edu.cn/help/debian/
	cat <<- EOF > /etc/apt/sources.list.bak.bfsu
		# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
		deb http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware
		# deb-src http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName} main contrib non-free non-free-firmware

		deb http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware
		# deb-src http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName}-updates main contrib non-free non-free-firmware

		deb http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware
		# deb-src http://mirrors.bfsu.edu.cn/debian/ ${LINUXVersionName}-backports main contrib non-free non-free-firmware

		# 以下安全更新软件源包含了官方源与镜像站配置，如有需要可自行修改注释切换
		deb http://security.debian.org/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
		# deb-src http://security.debian.org/debian-security ${LINUXVersionName}-security main contrib non-free non-free-firmware
	EOF

	# 中科大 http://mirrors.ustc.edu.cn/help/debian.html
	cat <<- EOF > /etc/apt/sources.list.bak.ustc
		# 默认注释了源码仓库，如有需要可自行取消注释
		deb http://mirrors.ustc.edu.cn/debian ${LINUXVersionName} main contrib non-free non-free-firmware
		# deb-src http://mirrors.ustc.edu.cn/debian ${LINUXVersionName} main contrib non-free non-free-firmware
		deb http://mirrors.ustc.edu.cn/debian ${LINUXVersionName}-updates main contrib non-free non-free-firmware
		# deb-src http://mirrors.ustc.edu.cn/debian ${LINUXVersionName}-updates main contrib non-free non-free-firmware

		# backports 软件源，请按需启用
		# deb http://mirrors.ustc.edu.cn/debian ${LINUXVersionName}-backports main contrib non-free non-free-firmware
		# deb-src http://mirrors.ustc.edu.cn/debian ${LINUXVersionName}-backports main contrib non-free non-free-firmware
	EOF

	REPO_LIST="tsinghua bfsu ustc"
}

function vm_add_bakup_repo() {
	echo "正在添加备用的软件仓库地址"

	# 备份旧的
	cp -f /etc/apt/sources.list				/etc/apt/sources.list.bak.ubuntu

	if [ "${CURRENT_VM_ARCH}" == "amd64" ]; then
		vm_add_bakup_repo_amd64
		return
	fi

	if [ "${CURRENT_VM_ARCH}" == "arm64" ]; then
		vm_add_bakup_repo_arm64
		return
	fi
}

function is_host_usable() {
	tmphst=$1

	# echo "try0"
	"${app_home}/toybox" ping -c 3 ${tmphst}
	if [ $? -eq 0 ]; then return 0; fi

	# echo "try1"
	ndkwget https://${tmphst}
	if [ $? -eq 0 ]; then return 0; fi

	# echo "try2"
	/system/bin/ping -c 3 ${tmphst}
	if [ $? -eq 0 ]; then return 0; fi

	return 1
}

function dist_repo_switch() {
	vm_add_bakup_repo
	for repo in ${REPO_LIST}
	do
		rm -rf /etc/apt/sources.list
		cp  -f /etc/apt/sources.list.bak.${repo}  /etc/apt/sources.list
		tmphst=`cat /etc/apt/sources.list|grep http|grep "${repo}"|${ALINKER64} "${tools_dir}/busybox/busybox" awk -F '/' '{print $3}'|grep -v '^$'|head -n 1`

		is_host_usable ${tmphst}
		if [ $? -ne 0 ]; then
			echo "此仓库不可用：${tmphst}"
			echo ""
			continue
		fi

		echo "此仓库可使用：${tmphst}"
		echo ""
		apt update -y
		return
	done

	echo ""
	echo "当前网络下所有的下载仓库都不可用，请关掉app重试"
	while true; do bash; done
}

function vm_backup_bootup_scripts() {
	echo '===================================='
	echo2apk '正在备份启动脚本 ...'
	echo '===================================='
	mkdir -p /etc/droidvm/bootup_scripts/
	mkdir -p /etc/droidvm/bootup_scripts/tools/
	cp -f ${app_home}/droidvm_vars_setup.sh	/etc/droidvm/bootup_scripts/
	cp -f ${app_home}/controllee			/etc/droidvm/bootup_scripts/
	cp -f ${app_home}/nmftpsrv				/etc/droidvm/bootup_scripts/
	cp -f ${tools_dir}/startvm.sh			/etc/droidvm/bootup_scripts/tools/
	cp -f /etc/lsb-release    				/etc/lsb-release.ori
	cp -f /usr/lib/os-release 				/usr/lib/os-release.ori
}

function vm_setupgui() {
	if [ "${vmGraphicsx}" != "1" ]; then
		return
	fi
	. ${tools_dir}/setup-gui.sh
}

function vm_generate_uuid() {
	dbus-uuidgen > /var/lib/dbus/machine-id
}

function vm_replace_reboot_binary() {
	rm -rf /usr/sbin/reboot /usr/sbin/shutdown /usr/sbin/halt
	chmod 700 /exbin/reboot /exbin/shutdown /exbin/halt
}

function vm_clean_cache() {
	echo '===================================='
	echo '正在清包管理器缓存'
	(cd /var/cache && rm -rf *)
	apt-get clean

	rm -rf /tmp/*
	rm -rf /var/log/*
	echo2apk '安装已完成，请重新打开app'
	echo '===================================='
	echo '===================================='
}

vm_generate_uuid
vm_backup_bootup_scripts
vm_replace_reboot_binary
vm_copy_autoruns_scripts

dist_repo_set_ipv4_default
dist_repo_setup_ca
dist_repo_switch
dist_repo_setup_sudo

vm_add_user_droidvm

vm_setupgui
vm_clean_cache

rm -rf ${tools_dir}/run_once.sh
